package membased;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

import com.gash.scrape.*;

import net.spy.memcached.MemcachedClient;

public class Memcache {
    //static String server = "localhost";
    static String server = "192.168.10.6";
    static int port = 11211; 	//memcache port
    //static int port = 11311;	//membase port 
    static List<ParseObject> objects;
    
    public static void main(String[] args) throws Exception {
    	if(args.length == 2) {
    		server = args[0];
    		port = Integer.parseInt(args[1]);
    	}
        MemcachedClient cache = new MemcachedClient(new InetSocketAddress(server, port));
        cache.flush(); // clean start
        
        objects = FileParser.parse("testdata/manypages.txt");
        List<String> keyList = new ArrayList<String>();
        
        //Load database
        long t1 = System.currentTimeMillis();
        loadDB(cache, objects, keyList); 
        long t2 = System.currentTimeMillis();
        long loadTime = t2-t1;

        //Perform title search
        String[] titleList = {"http://en.wikipedia.org/wiki/batch_file", "http://en.wikipedia.org/wiki/winfs", "http://en.wikipedia.org/wiki/google_file_system"};
        t1 = System.currentTimeMillis();
        titleSearch(cache, titleList);
        t2 = System.currentTimeMillis();
        long titleSearchT = t2-t1;
        
        //Retrieve all titles
        t1 = System.currentTimeMillis();
        titleSearch(cache, keyList);
        t2 = System.currentTimeMillis();
        long allTitles = t2-t1;
        
        //Perform keyword search
        String[] keywordList = {"javascript", "database", "query"};
        t1 = System.currentTimeMillis();
       // keywordSearch(cache, keywordList);
        t2 = System.currentTimeMillis();
        long keywordSearch = t2-t1;
        
        //Perform keyword search
        t1 = System.currentTimeMillis();
       // keywordSearch(cache, keyList);
        t2 = System.currentTimeMillis();
        long allKeywords = t2-t1;
       
        cache.shutdown();   
               
        System.out.println("\nStats:");
        System.out.println("Time to loading DB: " + loadTime + " ms (" + new Float(loadTime/1000f) +"sec)");
        System.out.println("Time to fetch " + titleList.length +" titles: " + titleSearchT + " ms (" + new Float(titleSearchT/1000f) + " sec)" );
        System.out.println("Time to fetch " +keyList.size() +" titles: " + allTitles + " ms (" + new Float(allTitles/1000f) + " sec)" );        
        System.out.println("Time to fetch " + keyList.size() +" keywords: " + keywordSearch + " ms (" + new Float(keywordSearch/1000f) + " sec)" );
        System.out.println("Time to fetch all keywords: " + allTitles + " ms (" + new Float(allTitles/1000f) + " sec)" );        
    }
    
    public static void titleSearch(MemcachedClient cache, String[] keyList) {
    	System.out.println("Performing search.");
    	ParseObject out;
        for(int i = 0; i < keyList.length; i++) {
        	out = (ParseObject)cache.get(keyList[i]);
        	if(out != null)
        		out.objectPrinter();
        }              
    }
   
    public static void titleSearch(MemcachedClient cache, List<String> keyList) {
    	System.out.println("Performing search.");
    	ParseObject out;
        for(int i = 0; i < keyList.size(); i++) {
        	out = (ParseObject)cache.get(keyList.get(i));
        	if(out != null)
        		out.objectPrinter();
        }              
    }
    
   
    public static void keywordSearch(MemcachedClient cache, String[] keywordList) {
    	System.out.println("Performing search.");
    	ParseObject out;
    	String key;
        for(int i = 0; i < keywordList.length; i++) {
        	 key = (String)cache.get(keywordList[i]);
        	// cache.get(keywordList[i], String);
        	 out = (ParseObject)cache.get(key);
        	 out.objectPrinter();
        }              
    }
   
    public static void keywordSearch(MemcachedClient cache, List<String> keyList) {
    	System.out.println("Performing search.");
    	ParseObject out;
    	Map<String, Object> o;
    	o = cache.getBulk(keyList);
        
    	/*
        for(int i = 0; i < 3; i++) {
           	out = (ParseObject)cache.get(keyList.get(i));
           	out.objectPrinter();
         } 
            */             
       }
   
    public static void loadDB(MemcachedClient cache, List<ParseObject> parsed, List<String> keys) {
    	ParseObject obj;
    	System.out.println("Loading DB");
    	for(int i = 0; i < parsed.size(); i++) {
    		obj = parsed.get(i);
    		
			String key = obj.url;
	    	String kwIndex = null;
	    	keys.add(obj.url);
	    	//add object into the database
	    	cache.add(key, 0, obj);
	 
	    	
	    	//create/append to Keyword index
	    	for(int j = 0; j < obj.keywords.size(); j++) {
	    		kwIndex = obj.keywords.get(j);
	    		if(kwIndex == null) { 
	    			kwIndex = "";
	    		}
	    		if((kwIndex.equals(""))) 
	    			break;
	    		//Does the index exist, if not create new index
	    		else if(cache.get(kwIndex) == null) {
	    			cache.add(kwIndex, 0, obj.url);
	    		}
	    		//the index does exist
	    		else {
	    			cache.append(0, kwIndex, obj.url);		
	    		}
	    		//keys.add(kwIndex);
	    	}
	    	/*
	    	//create/append title index
	    	//System.out.println("Building title index");
			String tIndex = obj.url;
			//Does the index exist, if not create new index
			if(cache.get(tIndex).equals(null)) {
				cache.set(tIndex, 0, obj.url);
			}
			//the index does exist
			else {
				cache.append(0, tIndex, obj.url);		
			} 
			*/
			obj = null;
			//System.out.print(".");
    	}
    	System.out.println("Database loaded and indexes created!");
    }
}